﻿using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using TUlingWpf.Services;
using TUlingWpf.ViewModels;
using TUlingWpf.Views;

namespace TUlingWpf
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public new static App? Current = (App)Application.Current;
        public IServiceProvider? Service { get; private set; }

        public App()
        {
            Service = ConfigureServices();
            this.InitializeComponent();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            //启动主窗体
            Service.GetService<MainWindow>()?.Show();
        }

        private IServiceProvider? ConfigureServices()
        {
            var services = new ServiceCollection();

            // 注册基础服务
            services.AddSingleton<UserSession>();

            // 自动注册所有View和ViewModel
            AutoRegisterBySuffix(services, "View");
            AutoRegisterBySuffix(services, "ViewModel");
            AutoRegisterBySuffix(services, "MainWindow");
            return services.BuildServiceProvider();
        }

        private void AutoRegisterBySuffix(IServiceCollection services, string suffix)
        {
            // 获取当前程序集
            var assembly = Assembly.GetExecutingAssembly();

            // 筛选以指定后缀结尾的非抽象类
            var types = assembly.GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract && t.Name.EndsWith(suffix));

            foreach (var type in types)
            {
                services.AddSingleton(type);
                Debug.WriteLine($"✅ 已自动注册 {type.Name}");
            }
        }
    }
}